package algorithms.que12;

/**
 * @功能
 * @创建时间 2020/6/21
 */
public class Rational16 {
    private final long num;
    private final long den;

    public Rational16(long numerator, long denominator)
    {
        if (denominator == 0)
            throw new RuntimeException("Denominator is zero");
        long g = gcd(numerator, denominator);

        if (denominator < 0)
            g = -g;

        this.num = numerator / g;
        this.den = denominator / g;
    }

    public Rational16 plus(Rational16 b)
    {   assert(den < Integer.MAX_VALUE && den > Integer.MIN_VALUE);
        assert(b.den < Integer.MAX_VALUE && b.den > Integer.MIN_VALUE);
        long d = den * b.den;
        long n = num * b.den + den * b.num;
        return new Rational16(n, d);
    }

    public Rational16 minus(Rational16 b)
    {   assert(den < Integer.MAX_VALUE && den > Integer.MIN_VALUE);
        assert(b.den < Integer.MAX_VALUE && b.den > Integer.MIN_VALUE);
        long d = den * b.den;
        long n = num * b.den - den * b.num;
        assert (d>0);
        assert (n>0);
        return new Rational16(n, d);
    }

    public Rational16 times(Rational16 b)
    {
        return new Rational16(num * b.num, den * b.den);
    }

    public Rational16 divides(Rational16 b)
    {
        return new Rational16(num * b.den, den * b.num);
    }

    public boolean equals(Rational16 that)
    {
        if (this == that) return true;
        if (that == null) return false;
        if (this.getClass() != that.getClass()) return false;
        return (num == that.num && den == that.den);
    }

    private static long gcd(long m, long n)
    {
        if (m < 0) m = -m;
        if (n < 0) n = -n;
        if (n == 0) return m;
        return gcd(n, m % n);
    }

    public String toString()
    {
        if (this.den == 1)
            return String.format("%d", this.num);
        return String.format("%d/%d", this.num, this.den);
    }


}
